<template>
  <!--tabs容器-->
  <div class="tabs-box" :style="tabContainer" v-if="data.entityId">
    <!--标签页容器-->
    <div
      v-if="type === 'section' || type === 'multiSection'"
      :style="tabHeader"
      class="tabs-nav-wrap"
    >
      <ul :style="tabHeaderUl">
        <li
          class="nav-tab"
          v-for="(title, index) in titlesToHideIndex > 0
            ? titles.slice(0, titlesToHideIndex)
            : titles"
          :key="index"
          :class="{ 'is-active': index === data.tabIndex }"
          :style="index === data.tabIndex ? activeStyle : ''"
          @click="selectTab(index, true)"
          :title="title.title"
        >
          {{ title.title }}
        </li>
      </ul>
      <!--图标-->
      <div
        v-if="isShowMoreBtn"
        :class="['tabs-more', { 'font-more': !isShowIcon }]"
        @click="openMorePage"
        :style="{
          lineHeight: `${sectionStyle.sectionHeaderTabsHeight}px`,
          height: `${sectionStyle.sectionHeaderTabsHeight}px`
        }"
      >
        <i v-if="isShowIcon" :class="sectionStyle.sectionMoreButtonIcon"></i>
        <a v-else>{{ moreButtonData.sectionMoreButtonText }}</a>
      </div>
      <!-- 多栏目超出隐藏 -->
      <HideMore
        :titlesToHide="titlesToHide"
        :selected="data.tabIndex"
        :selectTab="selectTab"
        :sectionStyle="sectionStyle"
        :hideMoreRightLen="hideMoreRightLen"
        :titlesToHideIndex="titlesToHideIndex"
        v-if="titlesToHide.length > 0"
      />
    </div>
    <!--组合栏目-->
    <div v-else class="tabs-two">
      <!--图标-->
      <div
        v-if="isShowMoreBtn"
        :class="['tabs-more', { 'font-more': !isShowIcon }]"
        @click="openMorePage"
        :style="{
          lineHeight: `${sectionStyle.sectionHeaderTabsHeight}px`,
          height: `${sectionStyle.sectionHeaderTabsHeight}px`,
          top: `-${sectionStyle.sectionHeaderTabsHeight}px`
        }"
      >
        <i v-if="isShowIcon" :class="sectionStyle.sectionMoreButtonIcon"></i>
        <a v-else>{{ moreButtonData.sectionMoreButtonText }}</a>
      </div>
      <ComposeTabs :contentWidth="contentWidth" :dataList="data.children" :selectTab="selectTab" />
    </div>
    <!--所有pane组件使用的slot容器-->
    <div :style="tabBody" class="tabs-content">
      <SectionGroup
        v-if="data.children && data.children.length > 0"
        :key="data.tabIndex"
        :data="data.children[data.tabIndex]"
        :sectionThemeData="sectionThemeData"
        :sectionStyle="sectionThemeData.sectionTheme"
        :customStyle="
          data.children[data.tabIndex].customStyle ? data.children[data.tabIndex].customStyle : {}
        "
        :entityId="data.children[data.tabIndex].entityId"
        :contentWidth="contentWidth"
        :type="data.children[data.tabIndex].type"
        :isMultiSection="isMultiSection"
      />
      <ContentPanel
        v-else
        :key="data.tabIndex"
        :containerStyle="{
          borderBottomLeftRadius: `${sectionThemeData.sectionTheme.sectionPanelBorderRadius}px`,
          borderBottomRightRadius: `${sectionThemeData.sectionTheme.sectionPanelBorderRadius}px`,
          overflow: 'hidden'
        }"
        :sectionStyle="sectionThemeData.sectionTheme"
        :sectionThemeData="sectionThemeData"
        :sectionData="data.sectionData"
        :setSectionData="(fetchedData) => setSectionData(data.sectionData, fetchedData)"
        :contentWidth="contentWidth"
        :entityId="data.entityId"
        :panel="data"
      />
    </div>
  </div>
</template>

<script>
  import ComposeTabs from './compose-tabs.vue';
  import moreBtnConfig from '../../common/moreBtnConfig';
  import HideMore from './components/hide-more.vue';
  import ContentPanel from '@/components/tabs/content-panel';
  import SectionGroup from './section-group.vue';

  let ctxPath = window._basePath;
  export default {
    name: 'Tabs',
    components: {
      ComposeTabs,
      ContentPanel,
      HideMore,
      SectionGroup
    },
    props: {
      sectionThemeData: {
        type: Object
      },
      sectionStyle: {
        type: Object
        // default: () => {
        //   return {};
        // },
      },
      isMultiSection: {
        type: Boolean,
        default: false
      },
      data: {
        type: Object,
        default: () => ({})
      },
      type: {
        type: String,
        default: 'section'
      },
      entityId: {
        type: String
        // default: "isid",
      },
      customStyle: { type: Object },
      contentWidth: { type: Number }
    },
    data() {
      return {
        ctxPath,
        // tab标签页名
        titles: [],
        // 需隐藏标签index
        titlesToHideIndex: -1,
        // 需隐藏的标签数组
        titlesToHide: [],
        composeType: '1',
        // 栏目外容器样式
        // tabContainer: {},
        // header
        tabHeader: {},
        // 选中样式
        activeStyle: {},
        // 内容区样式
        // tabBody: {},
        showMoreBtnList: moreBtnConfig.showMoreBtnList,
        newsSectionList: moreBtnConfig.newsSectionList,
        tabHeaderUl: {}
      };
    },
    computed: {
      // 更多显示图标
      isShowIcon() {
        return this.sectionStyle.sectionMoreButtonType === 'icon';
      },
      currentData() {
        return this.data.children ? this.data.children[this.data.tabIndex] : this.data;
      },
      isShowMoreBtn() {
        return this.showMoreBtnList.includes(this.currentData.template);
      },
      //更多按钮接口请求过来之后构建的
      moreButtonData() {
        return this.getMoreData(this.currentData) || {};
      },
      // 更多数据跳转
      // url() {
      //     // return `${this._basePath}/newsData.do?method=newsIndex&spaceType=3`;
      //     return "http://a82.seeyoncd.com/seeyon/newsData.do?method=newsIndex&spaceType=3";
      // },
      // 超出隐藏图标距离右边的值
      hideMoreRightLen() {
        let len = 35;
        let moretext =
          this.moreButtonData.sectionMoreButtonText || this.sectionStyle.sectionMoreButtonText;
        if (this.sectionStyle.sectionMoreButtonType !== 'icon') {
          len = moretext.length * 12 + 15;
        }
        return len;
      },
      // 栏目背景色
      tabContainerBg() {
        let tabContainerBg;
        if (this.customStyle) {
          tabContainerBg = this.customStyle.backgroundColor;
        } else {
          tabContainerBg =
            this.data.sectionData && this.data.sectionData.options.backgroundColor
              ? this.data.sectionData.options.backgroundColor
              : this.sectionStyle.sectionPanelBgc;
        }
        return tabContainerBg;
      },
      tabContainer() {
        let tabContainer = {};
        // 是否显示外框阴影
        if (this.sectionStyle.sectionPanelBoxShadow == 1) {
          tabContainer['boxShadow'] = '0px 3px 6px 0px rgb(221 221 221 / 35%)';
        }
        // 是否显示栏目外框，1-显示外框，0-不显示
        if (this.sectionStyle.sectionPanelBorderDisplay == 1) {
          tabContainer['borderRadius'] = `${this.sectionStyle.sectionPanelBorderRadius}px`;
          tabContainer['border'] = `1px solid ${this.sectionStyle.sectionPanelBorderColor}`;
        }
        tabContainer['backgroundColor'] = this.tabContainerBg;
        tabContainer['backgroundImage'] = `url(${this.sectionStyle.sectionPanelBgi || ''})`;

        if (this.isMultiSection) {
          tabContainer['borderRadius'] = `${this.sectionStyle.sectionPanelBorderRadius}px`;
        }
        // 外容器
        return tabContainer;
      },
      tabBody() {
        return {
          backgroundColor: `${
            this.customStyle.isSectionBg ? this.tabContainerBg : this.sectionStyle.sectionBodyBgc
          }`,
          backgroundImage: `url(${
            this.sectionStyle.sectionBodyBgi ? this.sectionStyle.sectionBodyBgi : ''
          })`,
          color: this.sectionStyle.sectionBodyColor,
          borderBottomLeftRadius: `${this.sectionStyle.sectionPanelBorderRadius}px`,
          borderBottomRightRadius: `${this.sectionStyle.sectionPanelBorderRadius}px`
        };
      }
    },
    created() {
      if (this.data.entityId) {
        // 拿到tab的title属性
        this.createTitles();
        this.initStyle();
        this.getParentTabBoxBg(this.data);
      }
    },
    methods: {
      setSectionData(sectionData, data) {
        sectionData.data = data;
      },
      // 组合栏目的背景色
      getParentTabBoxBg(panel) {
        // const bg = panel.children[panel.tabIndex].children[panel.children[panel.tabIndex].tabIndex].sectionData.options.backgroundColor
        // return bg
        // console.log('this.getPannelBg(panel)',this.getPannelBg(panel))
        if (panel.customStyle) {
          const { isSectionBg, sectionBgColor } = this.getPannelBg(panel);
          panel.customStyle.backgroundColor = sectionBgColor;
          panel.customStyle.isSectionBg = isSectionBg;
        }
      },
      getPannelBg(panel) {
        if (panel.children) {
          return this.getPannelBg(panel.children[panel.tabIndex]);
        } else {
          return {
            isSectionBg: panel.sectionData?.options.backgroundColor,
            sectionBgColor: panel.sectionData?.options.backgroundColor
              ? panel.sectionData?.options.backgroundColor
              : this.sectionThemeData.sectionTheme.sectionPanelBgc
          };
        }
      },
      initStyle() {
        // 初始化样式
        // console.log("sectionStyle: ", this.sectionStyle);
        if (!this.isMultiSection) {
          this.outSideStyle();
        }

        // tab的header样式，在“栏目外框”中设置的
        this.tabHeader = {
          backgroundColor: this.sectionStyle.sectionHeaderBgc,
          backgroundImage: `url(${this.sectionStyle.sectionHeaderBgi || ''})`,
          borderBottom: `1px solid ${this.sectionStyle.sectionHeaderBottomBorderColor}`,
          fontSize: `${this.sectionStyle.sectionHeaderTabsFontSize}px`,
          height: `${this.sectionStyle.sectionHeaderTabsHeight}px`,
          lineHeight: `${this.sectionStyle.sectionHeaderTabsHeight}px`,
          color: this.sectionStyle.sectionHeaderTabsColor,
          borderTopLeftRadius: `${this.sectionStyle.sectionPanelBorderRadius}px`,
          borderTopRightRadius: `${this.sectionStyle.sectionPanelBorderRadius}px`
        };
        this.tabHeaderUl = {
          height: `${this.sectionStyle.sectionHeaderTabsHeight}px`
        };
        this.activeStyle = {
          color: this.sectionStyle.sectionHeaderTabsCurrentColor,
          borderBottom: `2px solid ${this.sectionStyle.sectionHeaderTabsCurrentLineColor}`
        };
      },
      // 栏目外框的一些样式
      outSideStyle() {
        if (this.type !== 'section') {
          // 添加line-height属性
          this.tabHeader.lineHeight = `${this.sectionStyle.sectionHeaderTabsHeight}px`;
        }
      },
      /**
       * @description: 显示更多数据
       */
      createTitles() {
        const { children, type, name } = this.data;
        this.titles =
          children && type !== 'sectionGroup'
            ? children.map((d) => ({
                title: d.name,
                icon: 'vportal vp-personality-icon0'
              }))
            : [{ title: name || '', icon: 'vportal vp-personality-icon0' }];
        // setTimeout(() => {
        //     this.selectTab(this.selected);
        // });
        // 计算栏目是否超出
        let _currentTabFontSize = this.sectionStyle.sectionHeaderTabsFontSize
          ? this.sectionStyle.sectionHeaderTabsFontSize
          : 16;
        let _curentTabTempWidth = 40;
        for (let i = 0; i < this.titles.length; i++) {
          let _currentTabWidth = _currentTabFontSize * this.titles[i].title.length + 30 + 30;
          _curentTabTempWidth += _currentTabWidth;
          if (_curentTabTempWidth > this.contentWidth) {
            this.titlesToHideIndex = i;
            break;
          }
        }
        if (this.titlesToHideIndex == 0 && this.titles.length > 1) {
          this.titlesToHide = this.titles.slice(1);
          this.titlesToHideIndex = 1;
        }
        if (this.titlesToHideIndex > 0) {
          this.titlesToHide = this.titles.slice(this.titlesToHideIndex);
        }
      },
      openMorePage() {
        const data = this.currentData;
        const sectionData = data.sectionData.data;
        //图片新闻取全的
        const rows = sectionData.rowsFull || sectionData.rows;
        vPortal.template = data.template;
        switch (data.template) {
          //公告
          case 'groupTopBulletinSection':
          case 'groupBulletinSection':
          case 'singleBoardGroupBulletinSection':
          case 'singleScrollTempleteNormal':
          case 'singleBoardBulSection':
          case 'bulletinSection':
          case 'bulletinTopSection':
            vPortal.bulletinData = rows;
          //第一项是焦点新闻、第二项是最新
          default:
            if (!rows) {
              vPortal.news = [];
            } else {
              vPortal.news = [rows.filter((row) => row.focus), rows];
            }
            break;
        }
        window.open(
          `${this.moreButtonData.url}?template=${data.template}&dataFile=${data.sectionData.dataFile}`,
          '_blank'
        );
      },
      /**
       * @description: 选中页签后触发事件
       * @param {Number} selectIndex 当前index值
       * @param {Boolean} isParent 是否是一级的父元素切换
       */
      selectTab(selectIndex = 0, isParent = false) {
        if (!this.data.children) return;
        this.setIndex(this.data, selectIndex, isParent);
      },
      setIndex(data, selectIndex, isParent) {
        data.tabIndex = selectIndex;
        //切换的时候重新设置背景色
        this.getParentTabBoxBg(this.data);
        //吧二级置为第一个
        if (isParent) {
          const children = data.children[selectIndex];
          if (children.children) {
            children.tabIndex = 0;
          }
        }
      },
      /**
       * @description: 获取更多按钮url
       * @param {Object} data 当前选中，影响“更多”的数据
       * @return {*}
       */
      getMoreData(data) {
        // 更多按钮显示
        const moreButton =
          data.sectionData && data.sectionData.data && data.sectionData.data.moreButton;
        if (moreButton) {
          let lastUrl = '';
          switch (data.template) {
            case 'groupTopBulletinSection':
            case 'groupBulletinSection':
            case 'singleBoardGroupBulletinSection':
            case 'singleBoardBulSection':
            case 'bulletinSection':
            case 'bulletinTopSection':
              lastUrl = '/entry/bulletin.html';
              break;
            default:
              lastUrl = '/entry/news.html';
          }
          return {
            sectionMoreButtonText: this.sectionStyle.sectionMoreButtonText || moreButton.label,
            url: this.isShowMoreBtn ? this.ctxPath + lastUrl : ''
          };
        }
      }
    }
  };
</script>
<style lang="scss">
  .tabs-box {
    .tabs-box {
      border: 0 !important;
    }
  }
</style>
<style lang="scss" scoped>
  .tabs-box {
    //width: 500px;
    height: 100%;
    background: transparent;
    background: #fff;
    // margin: 10px 0px;
    //   padding:0px 20px ;

    .tabs-more {
      color: rgba(38, 96, 213, 0.4);

      &:hover {
        cursor: pointer;
      }
    }

    .tabs-nav-wrap {
      position: relative;
      padding: 0 20px;
      border-bottom: 1px solid rgba(38, 96, 213, 0.4);

      > ul {
        // position: absolute;
        // bottom: -1px;
        // display: inline-block;
        padding: 0;
        margin: 0;
        list-style: none;

        > li {
          font-weight: 400;
          position: relative;
          top: -1px;
          display: inline-block;
          // padding: 12px 0;
          margin: 0 30px 0 0;
          cursor: pointer;
          border-bottom: 2px solid transparent;

          &.nav-tab {
            max-width: 70%;
            overflow: hidden; //溢出隐藏
            text-overflow: ellipsis;
            white-space: nowrap; //禁止换行
          }
        }

        .is-active {
          border-bottom: 2px solid #1890ff;
        }
      }

      > div {
        position: absolute;
        top: 50%;
        right: 20px;
        float: right;
        margin-top: -20px;

        > i {
          width: 20px;
          height: 20px;
        }
      }
    }

    .tabs-two {
      position: relative;

      > .tabs-more {
        position: absolute;
        right: 20px;
      }

      .compose-name {
        // line-height: 40px;
        display: inline-block;
      }
    }

    .tabs-content {
      margin: 0;
      // padding: 10px 15px;
      // overflow: hidden;
    }
  }
</style>

<style lang="scss">
  // .pannel-list-wrapper {
  //     ul {
  //         li {
  //             height: var(--sectionBodyLineHeight) !important;
  //             line-height: var(--sectionBodyLineHeight) !important;
  //             border-bottom-width: 1px;
  //             border-bottom-style: solid;
  //             border-bottom-color: var(--sectionBodyLineBottomBoderColor);
  //             &:nth-child(2n) {
  //                 background-color: var(--sectionBodyDlBgc);
  //             }
  //         }
  //     }
  // }
</style>
